// 管理员下拉菜单专用处理脚本
document.addEventListener('DOMContentLoaded', () => {
  console.log('管理员下拉菜单脚本已加载');
  
  // 设置主按钮
  setupDropdown('admin-menu-button', 'admin-dropdown-menu');
  
  // 设置备用按钮
  setupDropdown('admin-menu-button-fallback', 'admin-dropdown-menu-fallback');

  function setupDropdown(buttonId, menuId) {
    const button = document.getElementById(buttonId);
    const menu = document.getElementById(menuId);
    
    if (!button || !menu) {
      console.log(`未找到元素: ${buttonId} 或 ${menuId}`);
      return;
    }
    
    console.log(`找到下拉菜单元素: ${buttonId}`);
    
    // 初始化样式
    menu.style.display = 'none';
    menu.style.position = 'fixed';
    menu.style.zIndex = '9999';
    menu.style.backgroundColor = '#FFFFFF';
    menu.style.boxShadow = '0 4px 6px rgba(0, 0, 0, 0.1), 0 1px 3px rgba(0, 0, 0, 0.08)';
    menu.style.borderRadius = '0.375rem';
    menu.style.overflow = 'hidden';
    
    // 点击按钮显示/隐藏菜单
    button.addEventListener('click', (e) => {
      e.preventDefault();
      e.stopPropagation();
      
      const isExpanded = button.getAttribute('aria-expanded') === 'true';
      
      // 先关闭所有菜单
      document.querySelectorAll('[id^=admin-dropdown-menu]').forEach(m => {
        m.style.display = 'none';
      });
      
      document.querySelectorAll('[id^=admin-menu-button]').forEach(b => {
        b.setAttribute('aria-expanded', 'false');
      });
      
      if (!isExpanded) {
        console.log(`显示菜单: ${menuId}`);
        
        // 计算位置
        const rect = button.getBoundingClientRect();
        menu.style.top = `${rect.bottom + window.scrollY}px`;
        menu.style.left = `${rect.left + window.scrollX}px`;
        
        // 显示菜单
        menu.style.display = 'block';
        button.setAttribute('aria-expanded', 'true');
        
        // 确保菜单在视口内
        const menuRect = menu.getBoundingClientRect();
        if (menuRect.right > window.innerWidth) {
          menu.style.left = `${window.innerWidth - menuRect.width - 10}px`;
        }
        
        if (menuRect.bottom > window.innerHeight) {
          menu.style.top = `${rect.top - menuRect.height}px`;
        }
      }
    });
  }
  
  // 点击其他地方关闭菜单
  document.addEventListener('click', (e) => {
    if (!e.target.closest('[id^=admin-menu-button]') && 
        !e.target.closest('[id^=admin-dropdown-menu]')) {
      
      document.querySelectorAll('[id^=admin-dropdown-menu]').forEach(menu => {
        menu.style.display = 'none';
      });
      
      document.querySelectorAll('[id^=admin-menu-button]').forEach(button => {
        button.setAttribute('aria-expanded', 'false');
      });
    }
  });
}); 